﻿using System;
using System.Text.RegularExpressions;
using Validity.Contexts;
using Validity.Localization;
using Validity.Rules;

namespace Validity
{
  public static class MatchesPatternConstraint
  {
    public static IConditionalValidationContext<TObject, String> MatchesPattern<TObject>(this IValidationContext<TObject, String> context, String pattern)
    {
      return context.MatchesPattern(pattern, RegexOptions.None);
    }

    public static IConditionalValidationContext<TObject, String> MatchesPattern<TObject>(this IValidationContext<TObject, String> context, String pattern, RegexOptions options)
    {
      Verify.False(String.IsNullOrEmpty(pattern));

      Regex regex = new Regex(pattern, options);

      context.AddRule(new Rule<TObject, String>(
        (obj, val) => regex.IsMatch(val ?? String.Empty),
        (obj, val) => String.Format(RuleViolations.PatternMatch, pattern)
      ));

      return new ConditionalValidationContext<TObject, String>(context);
    }
  }
}
